/*
 * Copyright 2012 Chris Uyehara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.chrisuyehara.vista.rpc.parameters;

import com.chrisuyehara.vista.rpc.client.RPCString;


/**
 * Class description
 *
 *
 * @version        v1.0, 2014-01-20
 * @author         Jim Horner
 */
public class GlobalParameter implements Parameter {

    /** Field description */
    public static final String BROKER_VALUE = "3";

    /** Field description */
    private final RPCString rpcStringKey;

    /** Field description */
    private final RPCString rpcStringValue;

    /**
     * Constructs ...
     *
     *
     * @param key
     * @param value
     */
    public GlobalParameter(String key, String value) {

        super();

        StringBuilder sbKey = new StringBuilder();

        try {
            sbKey.append(Integer.parseInt(key));
        } catch (NumberFormatException e) {

            sbKey.append(key);

            if ( !key.startsWith("\"") || !key.endsWith("\"")) {

                if ( !key.startsWith("\"")) {
                    sbKey.insert(0, "\"");
                }

                if ( !key.endsWith("\"")) {
                    sbKey.append("\"");
                }
            }
        }

        if ((null == value) || "".equals(value)) {
            value = "\u0001";
        }

        this.rpcStringKey = new RPCString(sbKey.toString());
        this.rpcStringValue = new RPCString(value);
    }

    /**
     * Method description
     *
     *
     * @return
     */
    @Override
    public String toParameter() {

        StringBuilder sb = new StringBuilder();

        sb.append(BROKER_VALUE);
        sb.append(rpcStringKey.packString(PACK_STRING_LENGTH));
        sb.append(rpcStringValue.packString(PACK_STRING_LENGTH));
        sb.append("f");

        return sb.toString();
    }
}
